package io.geekidea.boot.persmanag.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import io.geekidea.boot.area.entity.Area;
import io.geekidea.boot.area.service.AreaService;
import io.geekidea.boot.auth.util.LoginUtil;
import io.geekidea.boot.common.PageDto;
import io.geekidea.boot.framework.annotation.Log;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.framework.response.ApiResult;
import io.geekidea.boot.persmanag.dto.PersManagDto;
import io.geekidea.boot.persmanag.dto.PersManagExcel;
import io.geekidea.boot.persmanag.entity.PersManag;
import io.geekidea.boot.role.entity.Role;
import io.geekidea.boot.persmanag.query.PersManagQuery;
import io.geekidea.boot.persmanag.service.PersManagService;
import io.geekidea.boot.role.service.RoleService;
import io.geekidea.boot.store.entity.Store;
import io.geekidea.boot.warehousentry.query.WarehousentryQuery;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * PersManagController 人员管理接口
 */
@Slf4j
@RestController
@Tag(name = "人员管理")
public class PersManagController {

    @Resource
    private PersManagService persManagService;
    @Resource
    private AreaService areaService;
    @Resource
    private RoleService roleService;


    @PostMapping("/list")
    @Operation(summary = "搜索人员管理",description = "按照多条件组合分页查询战区数据列表")
    public ApiResult seachList(@RequestBody PersManagQuery persManagQuery){
        List<PersManag> persManag = persManagService.getpersManagPageList(persManagQuery);
        int total = persManagService.getTotal(persManagQuery).getTotal();
        PageDto<PersManag> pageDto = new PageDto<>(persManag,total,persManagQuery.getPageSize(),persManagQuery.getPageIndex() + 1);
        return ApiResult.success(pageDto);
    }

    @PostMapping("/ares/list")
    @Operation(summary = "搜索所有战区")
    public ApiResult areaList(){
        List<Area> list = areaService.list();
        List<Map<String, Object>> areas = new ArrayList<>();
        for (Area area:list){
            String name = area.getName();
            Integer id = area.getId();
            Map<String,Object> areaMap = new HashMap<>();
            areaMap.put("name",name);
            areaMap.put("id",id);
            areas.add(areaMap);
        }
        return ApiResult.success(areas);
    }



    @PostMapping("/role/list")
    @Operation(summary = "搜索角色列表")
    public ApiResult roleList(){

        List<Role> list = roleService.list();
        List<Map<String, Object>> areas = new ArrayList<>();
        for (Role role:list){
            String name = role.getRole();
            Integer id = role.getId();
            Map<String,Object> areaMap = new HashMap<>();
            areaMap.put("name",name);
            areaMap.put("id",id);
            areas.add(areaMap);
        }

        return ApiResult.success(areas);

    }


    @PostMapping("/stores/list/{id}")
    @Operation(summary = "根据id查询门店")
    public ApiResult findStore(@PathVariable Integer id){
        List<Store> storeList = persManagService.getStoreList(id);
        return ApiResult.success(storeList);
    }


    @Operation(summary = "查询人员管理",description = "根据id查询人员")
    @GetMapping("/get/{id}")
    public ApiResult getPersManag(@PathVariable(value = "id") Integer id){
        PersManag persManag = persManagService.getPersManag(id);
        return ApiResult.success(persManag);
    }

    @DeleteMapping("/remove/{id}")
    @Operation(summary = "删除人员管理(真删慎用)",description = "根据id删除人员")
    public ApiResult removePersManag(@PathVariable(value = "id")Integer id){
        persManagService.removeById(id);
        return ApiResult.success("删除人员数据成功");
    }


    @PostMapping("/del/{id}")
    @Operation(summary = "逻辑删除人员管理",description = "根据id删除人员")
    public ApiResult del(@PathVariable Integer id){
        boolean update = persManagService.delById(id);
        if (!update){
            return ApiResult.success("删除失败");
        }
        return ApiResult.success("删除成功");
    }

    @PostMapping("/add")
    @Operation(summary = "添加人员管理",description = "添加人员")
    public ApiResult addPersManag(@RequestBody PersManagDto persManagDto) throws Exception {

        // StoreChange storeChangeEntity = new StoreChange();
        //    storeChangeEntity.setCreatedBy(LoginUtil.getUsername());
//        PersManag persManag = new PersManag();
//        persManag.setCreatedBy(LoginUtil.getUsername());
        persManagDto.setCreatedBy(LoginUtil.getUsername());
        boolean b = persManagService.addPersManag(persManagDto);
        if (!b){
            return ApiResult.success("添加失败");
        }
        return ApiResult.success("人员数据添加成功");
    }

    @PostMapping("/update")
    @Operation(summary = "修改人员管理",description = "修改人员")
    public ApiResult updatePers(@RequestBody PersManag persManag) throws Exception {
        persManag.setUpdatedBy(LoginUtil.getUsername());
        boolean b = persManagService.updatePersManag(persManag);
        if (!b){
            return ApiResult.success("修改失败");
        }
        return ApiResult.success("人员数据修改成功");
    }



    @PostMapping("/download")
    @Operation(tags = "Post",description = "下载文件")
    public void download(@RequestBody PersManagQuery persManagQuery,HttpServletResponse response){
        //WarehousentryQuery warehousentryQuery = new WarehousentryQuery();

        List<PersManagExcel> list = persManagService.getDownloadList(persManagQuery);
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String excelName = URLEncoder.encode("人员管理"+ LocalDateTime.now(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
            // 以字节流的形式输出响应正文
            outputStream = response.getOutputStream();
            try (ExcelWriter excelWriter = EasyExcel.write(outputStream, PersManagExcel.class).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
                excelWriter.write(list,writeSheet);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }


}
